package com.drd.dt.util;

import com.alibaba.fastjson.JSONObject;
import com.drd.dt.common.Constant;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 字符串工具
 */
public class StringUtil {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * @param keys 作为map的key
     * @param values 作为map的value
     */
    public static Map<String, String> StrsToMap(String keys, String values, Class c) throws BussinessException {
        Map<String, String> tempMap = new HashMap<String, String>();
        //存放实体类所有属性
        List<String> colStrs = new ArrayList<String>();
        Field[] fields = c.getDeclaredFields();
        for (Field field:fields) {
            colStrs.add(field.getName());
        }
        //如果传入的查询条件为空, 返回null
        if(StringUtils.isEmpty(keys) || StringUtils.isEmpty(values)){
            return null;
        }
        String[] keyArr = keys.split(Constant.SEPARATOR);
        String[] valueArr = values.split(Constant.SEPARATOR);
        if (keyArr.length == 1 || valueArr.length == 1){
            Boolean flag = colStrs.contains(keys);
            if (flag){
                tempMap.put(keys,values);
            }else{
                throw new BussinessException(BizExceptionEnum.PATAM_ERROR);
            }
            return tempMap;
        }
        if (keyArr.length != valueArr.length){
            return null;
        }else{
            for(int i = 0; i < keyArr.length; i++){
                Boolean flag = colStrs.contains(keyArr[i]);
                if (flag){
                    tempMap.put(keyArr[i], valueArr[i]);
                }else{
                    throw new BussinessException(BizExceptionEnum.PATAM_ERROR);
                }
            }
            return tempMap;
        }
    }


    /**
     * 将文件大小转换为字节
     * @param size
     * @return
     */
    public static Long corver2Byte(String size){
        String left;
        if (size.endsWith("KB")){
            left = StringUtils.left(size, size.length()-2);
            return (long)(Double.valueOf(left)*1024);
        }else if (size.endsWith("MB")){
            left = StringUtils.left(size, size.length()-2);
            return (long)(Double.valueOf(left)*1024 * 1024);
        }else if (size.endsWith("GB")){
            left = StringUtils.left(size, size.length()-2);
            return (long)(Double.valueOf(left)*1024 * 1024 * 1024);
        }else {
            return Long.valueOf(size);
        }
    }
    public static String getSql(JSONObject rule, String username){
        JSONObject from = rule.getJSONObject("from");
        String filename = from.getString("filename");
        String column = from.getJSONObject("structure").getString("column");
        if (from.getJSONObject("dsource").getString("engine").toUpperCase().equals("MYSQL")){
            return "SELECT " + column + " FROM " + filename;
        }else {
            String[] split = column.split(",");
            StringBuffer buffer = new StringBuffer();
            for (int i=0;i<split.length;i++){
                if (i <split.length-1){
                    buffer.append("\""+split[i]+"\",");
                }else {
                    buffer.append("\""+split[i]+"\"");
                }
            }
            return "SELECT " + buffer.toString() + " FROM " + username + ".\"" + filename+"\"";
        }
    }

    /**
     * 生成32位UUID
     *
     * @return UUID
     */
    public static String getUUid() {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        return uuid;
    }

    /**
     * 手机号码正则匹配
     **/
    public static boolean isMobileNO(String mobileNums) {
        /**
         * 判断字符串是否符合手机号码格式
         * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188,172
         * 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
         * 电信号段: 133,149,153,170,173,177,180,181,189,199
         * @param str
         * @return 待检测的字符串
         */
        String telRegex = "^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (StringUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }


    public static String filterEmoji(String source) {
        if (source != null && source.length() > 0) {
            return source.replaceAll("[\ud800\udc00-\udbff\udfff\ud800-\udfff]", "");
        } else {
            return source;
        }
    }

    /**
     * 获取 客户端IP
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        StringBuilder ip = null;
        //X-Forwarded-For：Squid 服务代理
        String ipAddresses = request.getHeader("X-Forwarded-For");
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //Proxy-Client-IP：apache 服务代理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //WL-Proxy-Client-IP：weblogic 服务代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //HTTP_CLIENT_IP：有些代理服务器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //X-Real-IP：nginx服务代理
            ipAddresses = request.getHeader("X-Real-IP");
        }
        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = new StringBuilder(ipAddresses.split(",")[0]);
        }
        //还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ip = new StringBuilder(request.getRemoteAddr());
        }
        return ip.toString();
    }

    /**
     * 获取京东拼多多订单时加密参数
     *
     *1-所有参数进行按照首字母先后顺序排列
     2-把排序后的结果按照参数名+参数值的方式拼接
     3-拼装好的字符串首尾拼接client_secret进行md5加密后转大写
     * @param map
     * @return
     */
    public static String sortByMapKey(Map map,String secret) throws Exception{
        List<Map.Entry<String, String>> sign = new ArrayList<>(map.entrySet());
        Collections.sort(sign, (o1, o2) -> o1.getKey().compareTo(o2.getKey()));
        StringBuilder builder = new StringBuilder();
        builder.append(secret);
        for (int i = 0; i < sign.size(); i++){
            builder.append(sign.get(i));
        }
        builder.append(secret);
        String str = builder.toString().replaceAll("=", "");
        String result = MD5Utils.MD5Encode(str, "utf8").toUpperCase();
        return result;
    }

    /**
     * 获取精确到秒的时间戳
     * @param date
     * @return
     */
    public static String getSecondTimestamp(Date date) throws Exception{
        if (null == date) {
            return "0";
        }
        String timestamp = String.valueOf(date.getTime()/1000);
        return String.valueOf(timestamp);
    }

    public static String getTimestampDate(String timestamp) {
        String str;
        SimpleDateFormat unix_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        str = unix_time.format(new Date(Long.valueOf(timestamp + "000")));

        return str;
    }

    /**
     * 获取昨天时间
     */
    public static String yesterdayDay(SimpleDateFormat sdf){
        Calendar calendar=Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,-24);
        String yesterdayDate = sdf.format(calendar.getTime());
        return yesterdayDate;
    }

    /**
     * 获取本月的第一天
     */
    public static String thisMonthFirstDay(SimpleDateFormat sdf){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH,1);
        calendar.add(Calendar.MONTH,0);
        String format = sdf.format(calendar.getTime());
        return format;
    }

    /**
     * 获取本月的最后一天
     */
    public static String thisMonthLastDay(SimpleDateFormat sdf){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH,0);
        calendar.add(Calendar.MONTH,1);
        String format = sdf.format(calendar.getTime());
        return format;
    }

    /**
     * 获取上个月的第一天
     */
    public static String preMonthFirstDay(SimpleDateFormat sdf){
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        String format = sdf.format(calendar.getTime());
        return format;
    }

    /**
     * 获取上个月的最后一天
     */
    public static String preMonthLastDay(SimpleDateFormat sdf){
        Calendar calendar=Calendar.getInstance();
        int month=calendar.get(Calendar.MONTH);
        calendar.set(Calendar.MONTH, month-1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String format = sdf.format(calendar.getTime());
        return format;
    }

    /**
     * 匹配传入ip地区
     */
    public String getIPLocation(String ip) throws Exception{
        String result = "";
        DbConfig config = new DbConfig();
        File file = new File("D:\\ipdata\\ip2region.db");
        if ( file.exists() == false ) {
            logger.info("Error: Invalid ip2region.db file");
            return "";
        }
        DbSearcher searcher = new DbSearcher(config, file.getAbsolutePath());
        //采用Btree搜索
        DataBlock block = searcher.btreeSearch(ip);
        //打印位置信息（格式：国家|大区|省份|城市|运营商）
        String region = block.getRegion();
        if (!org.springframework.util.StringUtils.isEmpty(region)){
            String[] split = region.split("\\|");
            result = split[0];
        }
        return result;
    }

    /**
     * 获取手机类型
     * @param agent
     * @return
     */
    public static String getMobileByUA(String agent){
        // 从user-agent中取出手机类型
        Pattern pattern = Pattern.compile(";\\s?[^;\\s]*?(\\s?\\S*?)\\s?(Build)?/");
        if(agent.indexOf("iPhone") != -1){
            return "iPhone";
        }
        try{
            agent=agent.replaceAll("; wv","");
            int start=agent.indexOf("Build/");
            String str=agent.substring(start+6);
            int end=agent.indexOf(")");
            String model=str.substring(0,end);
            return model;
        }catch(Exception e){
            return  "";
        }

       /* Matcher matcher = pattern.matcher(agent);
        String model = "";
        if (matcher.find()) {
            model = matcher.group(1).trim();
        }*/

    }

    /**
     * 计算时间差
     */
    public static String formatTime(String beginTime,Date now) throws Exception{
        SimpleDateFormat simpleFormat = Constant.y_M_d_H_m_s;
        Date time = simpleFormat.parse(beginTime);
        long begin = time.getTime();
        long to1 = now.getTime();
         /*秒差*/
        int seconds = (int) ((to1 - begin) / (1000));
        if (seconds <= 60){
            return seconds + "秒";
        }
         /*分钟差*/
        int minutes = seconds / 60;
        if (minutes <= 60){
            return minutes + "分钟";
        }
        /*小时差*/
        int hours = minutes / 60;
        if (hours <= 24){
            return hours + "小时";
        }
        /*天数差*/
        int days = hours / 24;
        if (days <= 30){
            return days + "天";
        }
        /*月数差*/
        int months = days / 30;
        return months + "个月";
    }

    /**
     * 淘宝搜索关键字匹配
     * @param keyWords
     * @return
     */
    public static String getKeyword(String keyWords) {
        switch (keyWords) {
            case "女装精品":
                keyWords = "女装 潮";
                break;

            case "男装精品":
                keyWords = "男装 潮";
                break;

            case "百货精品":
                keyWords = "家居 生活";

            case "9.9":
                keyWords = "9.9包邮 9.9";
                break;

            case "母婴精品":
                keyWords = "婴 幼儿";
                break;

            case "内衣精品":
                keyWords = "文胸";
                break;

            case "鞋包精品":
                keyWords = "头层皮";
                break;

            case "美妆精品":
                keyWords = "化妆";
                break;

            case "美食精品":
                keyWords = "零食";
                break;

            case "手机周边精品":
                keyWords = "手机";
                break;

            case "配饰精品":
                keyWords = "饰品 女";
                break;

            case "成人精品":
                keyWords = "成人 情趣";
                break;

            case "其他精品":
                keyWords = "热卖";
                break;

            case "鞋包":
                keyWords = "鞋 包";
                break;

            case "美妆":
                keyWords = "妆";
                break;

            case "手机周边":
                keyWords = "手机 抖音";
                break;

            case "成人":
                keyWords = "避孕套";
                break;

            case "其他":
                keyWords = "推荐";
                break;

            case "婴童服饰":
                keyWords = "童装";
                break;

            case "婴童寝居":
                keyWords = "儿童床";
                break;

            case "婴童洗护":
                keyWords = "儿童沐浴";
                break;

            case "喂养用品":
                keyWords = "婴儿奶粉";
                break;

            case "出行产品":
                keyWords = "婴儿推车";
                break;

            case "婴童湿巾":
                keyWords = "婴童湿纸巾";
                break;

            case "童桌童床":
                keyWords = "儿童桌";
                break;

            case "精选肉食":
                keyWords = "零食 肉食";
                break;

            case "坚果蜜饯":
                keyWords = "零食 坚果";
                break;

            case "河海生鲜":
                keyWords = "海鲜";
                break;

            case "妈咪包背婴带":
                keyWords = "婴儿背带";
                break;

            case "茶酒冲饮":
                keyWords = "饮品";
                break;

            case "粮油调味":
                keyWords = "调料";
                break;

            case "洗发造型":
                keyWords = "洗发";
                break;

            case "个人护理":
                keyWords = "护理";
                break;

            case "纸品湿巾":
                keyWords = "纸 湿巾纸";
                break;

            case "美容护肤":
                keyWords = "化妆品";
                break;

            case "洗浴用品":
                keyWords = "洗澡";
                break;

            case "衣服清洁":
                keyWords = "洗衣服 洗衣液 消毒液";
                break;

            case "驱蚊杀虫":
                keyWords = "蚊子";
                break;

            case "男士个护":
                keyWords = "男 护肤品";
                break;

            case "运动鞋服":
                keyWords = "运动套装";
                break;

            case "户外鞋服":
                keyWords = "户外服装";
                break;

            case "运动工具":
                keyWords = "健身器材";
                break;

            case "箱包配件":
                keyWords = "挂饰";
                break;

            case "背心T恤":
                keyWords = "背心 体恤";
                break;

            case "音像制品":
                keyWords = "音响 ";
                break;

            case "驱蚊灭虫":
                keyWords = "杀虫剂";
                break;

            case "绿植园艺":
                keyWords = "盆栽";
                break;

            case "桌游棋牌":
                keyWords = "桌游";
                break;

            case "人偶娃娃":
                keyWords = "玩具娃娃";
                break;

            case "模型手办":
                keyWords = "手办";
                break;

            case "美术兴趣":
                keyWords = "美术";
                break;

            case "毛笔相关":
                keyWords = "毛笔";
                break;

            case "洛丽塔":
                keyWords = "Lolita";
                break;

            case "乐器配件":
                keyWords = "乐器";
                break;

            case "教学用具":
                keyWords = "教学";
                break;

            case "户外广告":
                keyWords = "户外";
                break;

            case "古风外衣":
                keyWords = "古风 ";
                break;

            case "动漫影视周边":
                keyWords = "动漫";
                break;

            case "办公桌椅":
                keyWords = "办公桌";
                break;

            case "COS专区":
                keyWords = "COS道具";
                break;

            case "大家电":
                keyWords = "大型家用电器";
                break;

            case "厨房大电":
                keyWords = "厨房电器";
                break;

            case "生活电器":
                keyWords = "家店";
                break;

            case "商用电器":
                keyWords = "咖啡机";
                break;

            case "家庭影音":
                keyWords = "音响 电视";
                break;

            case "耳机配件":
                keyWords = "耳机";
                break;

            case "厨房电器":
                keyWords = "厨电";
                break;

            case "灯饰光源":
                keyWords = "台灯";
                break;

            case "装修建材":
                keyWords = "装修";
                break;

            case "咖啡相关":
                keyWords = "咖啡";
                break;

            case "杯类":
                keyWords = "杯";
                break;

            case "烧烤野炊":
                keyWords = "烧烤";
                break;

            case "机电五金":
                keyWords = "五金";
                break;

            case "电子原件":
                keyWords = "电子";
                break;

            case "电路线材":
                keyWords = "电线";
                break;

            case "安防监控":
                keyWords = "监控";
                break;

            case "艺术品":
                keyWords = "艺术";
                break;

            case "情爱玩具":
                keyWords = "情趣";
                break;

            case "情趣内衣":
                keyWords = "情趣睡衣";
                break;

            case "女用玩具":
                keyWords = "情趣用具";
                break;

            case "品牌电脑":
                keyWords = "电脑";
                break;

            case "交换机":
                keyWords = "路由";
                break;

            case "电脑硬件":
                keyWords = "电脑配件";
                break;

            case "相机":
                keyWords = "照相机";
                break;

            case "台式电脑":
                keyWords = "台式电脑组装";
                break;

            case "相机配件":
                keyWords = "镜头";
                break;

            case "身体护理":
                keyWords = "身体乳";
                break;

            case "短裤中裤":
                keyWords = "短裤";
                break;

            case "萌猫":
                keyWords = "猫活体";
                break;

            case "萌狗":
                keyWords = "狗活体";
                break;

            case "鱼水族":
                keyWords = "观赏鱼";
                break;

            case "鸟":
                keyWords = "鸟活体";
                break;

            case "龟":
                keyWords = "乌龟";
                break;
        }
        if (!org.springframework.util.StringUtils.isEmpty(keyWords)){
            if (keyWords.contains("】") && keyWords.startsWith("【") && !keyWords.endsWith("】")){
                keyWords = keyWords.split("】")[1];
            }
        }
        keyWords = keyWords.replaceAll("[+~^&—￥]", "");
        return keyWords;
    }
}
